package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.model.*;
import com.rongke.service.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version : Ver 1.0
 * @QuestionnaireController
 * @调查问卷Controller
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "/api/questionnaire")
@Transactional
public class QuestionnaireController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private QuestionnaireService questionnaireService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private QuestionOptionService questionOptionService;

    @Autowired
    private GoodsQuerstionService goodsQuerstionService;
    @Autowired
    private MuserService muserService;
    @Autowired
    private UserQuestionnaireService userQuestionnaireService;
    @Autowired
    private UserQuestionService userQuestionService;

    /**
     * @param querstionOption
     * @return 返回值JsonResp
     * @添加调查问卷
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addQuestionnaire(@RequestBody QuerstionOption querstionOption) {
        log.debug("添加调查问卷");
        Timestamp timestamp = new Timestamp(new Date().getTime());
        //问卷新增
        if (querstionOption.getNaireId() == null || "".equals(querstionOption.getNaireId())) {
            Questionnaire qn = new Questionnaire();
            qn.setTitle(querstionOption.getNaireTitle());
            qn.setBonus(querstionOption.getBonus());
            qn.setExpireTime(querstionOption.getExpireTime());
            qn.setType(querstionOption.getType());
            qn.setContent(querstionOption.getNaireContent());
            qn.setAddtime(timestamp);
            questionnaireService.insert(qn);
            querstionOption.setNaireId(qn.getId());//获取问卷ID
        }

        //问题新增
        Question qt = new Question();
        qt.setQuestionnaireId(querstionOption.getNaireId());
        qt.setTitle(querstionOption.getQuestionTitle());
        qt.setType(querstionOption.getQuestionType());
        qt.setAddtime(timestamp);
        questionService.insert(qt);

        //选项新增
        String[] options = querstionOption.getOptions().split(",");
        String[] content = querstionOption.getOptionContent().split(",");
        for (int i = 0; i < options.length; i++) {
            QuestionOption o = new QuestionOption();
            o.setContent(content[i]);
            o.setOptions(options[i]);
            o.setQuestionId(qt.getId());
            o.setQuestionnaireId(qt.getQuestionnaireId());
            o.setAddtime(timestamp);
            questionOptionService.insert(o);
        }

        //把添加的值传回前端显示 主要是问卷id 用来判断
        //List<QuerstionOption> list = new ArrayList<QuerstionOption>();
        //list.add(querstionOption);
        return JsonResp.ok(querstionOption.getNaireId());
    }

    /**
     * @param questionnaire
     * @return 返回值JsonResp
     * @修改调查问卷
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateQuestionnaire(@RequestBody Questionnaire questionnaire) {
        log.debug("修改调查问卷");
        questionnaireService.updateById(questionnaire);
        return JsonResp.ok(questionnaire);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找调查问卷
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectQuestionnaire(Long id) {
        log.debug("查找调查问卷");
        Map<String, Object> maps = new HashMap<>();
        //获取问卷
        Questionnaire questionnaire = questionnaireService.selectById(id);
        //获取问题
        EntityWrapper<Question> eques = new EntityWrapper<>();
        eques.eq("questionnaire_id", questionnaire.getId());
        List<Map<String, Object>> quesList = questionService.selectMaps(eques);
        //获取问题下的选项
        for (Map<String, Object> m : quesList) {
            EntityWrapper<QuestionOption> qot = new EntityWrapper<>();
            qot.in("question_id", m.get("id").toString());
            List<Map<String, Object>> optionList = questionOptionService.selectMaps(qot);
            m.put("optionList", optionList);
        }
        maps.put("questionnaire", questionnaire);
        maps.put("quesList", quesList);
        return JsonResp.ok(maps);
    }

    /**
     * @param questionnaire
     * @return 返回值JsonResp
     * @根据条件查找调查问卷
     */
    @RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
    public JsonResp selectQuestionnaireByCondition(@RequestBody Questionnaire questionnaire) {
        log.debug("根据条件查找调查问卷");
        if (questionnaire == null)
            return JsonResp.toFail("参数不能为空");
        List<Questionnaire> questionnaireList = questionnaireService.selectByCondition(questionnaire);
        return JsonResp.ok(questionnaireList);
    }


    /**
     * 首页显示
     *
     * @param page
     * @return 返回值JsonResp
     * @遍历问卷
     */
    @RequestMapping(value = "/selectAll", method = RequestMethod.GET)
    public JsonResp selectAll(Page page,Integer type) {
        log.debug("查找主页问卷列表");
        EntityWrapper<Questionnaire> qt = new EntityWrapper<>();
        if(null!=type){
            qt.eq("type",type);//问卷类型 1 试用众测问卷 2 有奖问卷
        }
        qt.orderBy("addtime",false);
        //qt.eq("Questionnaire_id", true);
        Page<Questionnaire> goodsPage = questionnaireService.selectPage(page, qt);
        return JsonResp.ok(goodsPage);
    }


    /**
     * @param id
     * @return 返回值JsonResp
     * @删除
     */
    @RequestMapping(value = "/deletequestionnaire", method = RequestMethod.GET)
    public JsonResp deleteExGoods(Long id) {
        log.debug("删除问卷 问题 选项");
        EntityWrapper<Question> qt = new EntityWrapper<>();
        qt.eq("questionnaire_id", id);
        EntityWrapper<QuestionOption> ot = new EntityWrapper<>();
        ot.eq("questionnaire_id", id);
        questionnaireService.deleteById(id);
        questionService.delete(qt);
        questionOptionService.delete(ot);
        return JsonResp.ok();
    }

    /**
     * 获取调查问卷详情
     * @param qnid 问卷id
     * @return
     */
    @RequestMapping(value = "/getQuestionaireDetailById",method = RequestMethod.GET)
    public JsonResp getQuestionaireDetailById(Long qnid){
        log.debug("获取调查问卷详情");
        Questionnaire questionnaire = questionnaireService.selectById(qnid);
            /*String ids = "";
            for(int i = 0;i<goodsList.size();i++){
                ids +=  goodsList.get(i).getQuestionnaireId()+ ",";
            }*/
        EntityWrapper<Question> qu = new EntityWrapper<>();
        qu.eq("questionnaire_id",qnid);
        List<Map<String,Object>> list = questionService.selectMaps(qu);
        Map<String,Object> maps = new HashMap<>();
        for (Map<String,Object> o:list) {
            EntityWrapper<QuestionOption> qot=new EntityWrapper<>();
            qot.in("question_id",o.get("id").toString());
            List<Map<String,Object>> oplist = questionOptionService.selectMaps(qot);
            for (Map<String,Object> m:oplist) {
                //查询该问题下的所有人数
                EntityWrapper<UserQuestion> uq = new EntityWrapper<>();
//                uq.eq("goods_id",id);
                uq.eq("querstion_id",o.get("id").toString());
                List<UserQuestion> uqlist = userQuestionService.selectList(uq);
                //查询该问题下该选项的总数
                EntityWrapper<UserQuestion> uqop = new EntityWrapper<>();
                uqop.eq("option_id",m.get("id").toString());
                List<UserQuestion> olist = userQuestionService.selectList(uqop);

                double count = uqlist.size();//该问卷下总人数
                double opsCount = olist.size();//该问卷下该选项的总人数
                m.put("count",count);
                m.put("opsCount",opsCount*100);
            }
            o.put("option",oplist);
        }
        maps.put("list",list);
        maps.put("naire",questionnaire);
        return JsonResp.ok(maps);
    }


}
